var uuidV4 = require('uuid/v4');
var Eventproxy = require('eventproxy');
var logger = require('../common/logger');
var models = require('../models');
var tools = require('../common/tools');
var config = require('config-lite');

exports.newGroup = function newGroup(req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);

  var user = req.user;
  var data = req.body;

  var groupId = req.params.uuid;

  ep.all('missing', function (attrs) {
    if (attrs.length) {
      return res.send_data({
        code: 400,
        message: '缺少字段' + attrs
      });
    }
  });
  var missingAttrs = tools.checkMissingAttr(data, ['name', 'areas']);
  if (missingAttrs.length) {
    return ep.emit('missing', missingAttrs);
  }

  data.name = data.name.trim();
  var areas = data.areas;

  ep.all('createGroup', 'createAreas', function() {
    return res.send_data();
  });

  data.event_uuid = user.event_uuid;

  if (groupId) { // 编辑职务
    models.group_area.destroy({
      where: {
        group_uuid: groupId
      }
    }).then(function() {
      models.group.update(data, {
        where: {
          uuid: groupId
        }
      }).then(function() {
        var _areas = areas.map(function(area) {
          return {
            group_uuid: groupId,
            area_uuid: area
          };
        });
        models.group_area.bulkCreate(_areas).then(function() {
          ep.emit('createAreas');
        });
        ep.emit('createGroup');
      });
    });
  } else {
    models.group.create(data).then(function(returnGroup) {
      var groupUUID = returnGroup.uuid;
  
      var _areas = areas.map(function(area) {
        return {
          group_uuid: groupUUID,
          area_uuid: area
        };
      });
      models.group_area.bulkCreate(_areas).then(function() {
        ep.emit('createAreas');
      });
      ep.emit('createGroup');
    });
  }
};

exports.getGroups = function getGroups(req, res, next) {
  var reqQuery = req.query;
  var page = parseInt(reqQuery.page, 10) || 1;
  page = page > 0 ? page : 1;
  var limit = models.group.pageLimit(Number(reqQuery.limit));
  var offset = models.group.pageOffset(page, limit);

  var condition = {
    offset: offset,
    limit: limit,
    where: {},
    include: [{
      model: models.area,
      through: true
    }, {
      as: 'belongto_area',
      model: models.area
    }]
  };

  var user = req.user;
  if (user.event_uuid) {
    condition.where.event_uuid = user.event_uuid;
  }

  models.group.findAndCountAll(condition).then(function(returnGroups) {
    return res.send_data({
      entities: returnGroups.rows,
      total_pages: models.group.totalPages(returnGroups.count, limit),
      current_page: page
    })
  });
};

exports.getGroupByUUID = function getGroupByUUID(req, res) {
  var groupUUID = req.params.uuid;

  models.group.findOne({
    where: {
      uuid: groupUUID
    },
    include: [{
      model: models.area,
      through: true
    }]
  }).then(function(returnGroup) {
    return res.send_data({
      entities: returnGroup
    });
  });
};

exports.delGroup = function delGroup(req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);

  var data = req.body;

  var groupId = req.params.uuid;

  ep.all('delGroup', 'delGroupAreas', function() {
    return res.send_data();
  });

  models.group.destroy({
    where: {
      uuid: groupId
    }
  }).then(function() {
    ep.emit('delGroup');
  });

  models.group_area.destroy({
    where: {
      group_uuid: groupId
    }
  }).then(function() {
    ep.emit('delGroupAreas');
  });
};
